package com.rongshu.sendmessage.activity;

import androidx.annotation.Nullable;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.lljjcoder.citywheel.CityPickerView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.adapter.CityAdapter;
import com.rongshu.sendmessage.adapter.QuAdapter;
import com.rongshu.sendmessage.adapter.ShengAdapter;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.LocationBean;
import com.rongshu.sendmessage.bean.UserInfoBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.Constant;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.view.bottomView.BottomSelectAreaDialog;
import com.rongshu.sendmessage.view.bottomView.CatogryBottomDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.rongshu.sendmessage.util.DialogUtil.hideProgress;

public class MyHomeActivity extends BaseActivity {
    private final int QIAN_MING_CODE = 0x42;
    //账号  15131649931 111111
    private final int USER_HAND_CODE = 0x53;
    private final int SEX_CODE = 0x96;
    private final int LOCATION_CODE = 0x89;
    private final int USER_NAME_CODE = 0x10;
    private TextView tv_user_name,tv_sex,tv_location,tv_qianming;
    private SimpleDraweeView iv_head;
    private RelativeLayout re_user_head;
    private Intent mIntent;
    private String qianming;
    private String userName;
    private int sex=-1;
    private CityPickerView mPicker;
    private String userHead;
    private String userId;
    private String loginUserName;

    private int shengPosition;
    private int shiPosition;
    private int quPosition=-1;
    private ListView listView,listView1,listView2;
    private ShengAdapter shengAdapter;
    private CityAdapter shiAdapter;
    private QuAdapter quAdapter;
    private List<LocationBean> shengList=new ArrayList<>();
    private List<LocationBean> shiList=new ArrayList<>();
    private List<LocationBean> quList=new ArrayList<>();
    private LinearLayout ll_listViews;
    private String defaultLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=this;
        setContentView(R.layout.activity_my_home);
        userId= MyApplication.mSettings.getString(HYContent.UserId,"");
        loginUserName= MyApplication.mSettings.getString(HYContent.LOGIN_NAME,"");
        initView();
        initData();

//        initImageView();
    }

//    private void initImageView() {
//        DialogUtil.showProgress(mContext);
//        Map<String, String> param = new HashMap<>();
//        param.put("username",loginUserName);
//        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
//        String url= new HYContent().GET_USER_HEAD_URL;
//        OkGo.<String>post(url).params(param).tag("GET_USER_HEAD_URL").execute(new StringCallback() {
//            @Override
//            public void onSuccess(Response<String> response) {
//                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
//                final int code = jr.getCode();
//                if(code > 0) {
//                    hideProgress();
//                    //测试地址
//                    String avatarUrl = jr.getData().getString("userPortraitUri");
//                    String baseUrl=avatarUrl
//                    ImageLoader.getInstance().displayImage("https://www.rongskj.com/ryb/uploads/20210809/1e383ebf-cba0-4153-a4ff-825369abb7c1.jpg",iv_head);
//                }else{
//                    ToastUtils.show(mContext,jr.getMsg());
//                    hideProgress();
//                }
//            }
//            @Override
//            public void onError(Response<String> response) {
//                ToastUtils.show(mContext,"操作失败");
//                hideProgress();
//            }
//        });
//    }

    private void initView() {
        tv_user_name=findViewById(R.id.tv_user_name);
        tv_qianming=findViewById(R.id.tv_qianming);
        TextView title=findViewById(R.id.title);
        title.setText("用户信息");
        findViewById(R.id.titleLayLeft).setOnClickListener(view->finish());
        tv_sex=findViewById(R.id.tv_sex);
        tv_location=findViewById(R.id.tv_location);
        iv_head=findViewById(R.id.iv_head);
        re_user_head=findViewById(R.id.re_user_head);
        String nick = MyApplication.mSettings.getString(HYContent.NickName, "");
        tv_user_name.setText(nick);
        defaultLocation = MyApplication.mSettings.getString(HYContent.LOCATION, "");
        tv_location.setText(defaultLocation);
        ll_listViews=findViewById(R.id.ll_listViews);
    }


    private void initData() {//点击“我的”获取相关数据信息
        DialogUtil.showProgress(mContext);
        Map<String, String> param = new HashMap<>();
//        String userId= MyApplication.mSettings.getString(HYContent.UserId,"");
        param.put("userId",userId);
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url= new HYContent().MY_HOME_DATA_URL;
        OkGo.<String>post(url).params(param).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                final int code = jr.getCode();
                if(code > 0) {
                    hideProgress();
                    UserInfoBean bean = JSON.parseObject(JSON.toJSONString(jr.getData()), UserInfoBean.class);
                    setData(bean);
                }else{
                    ToastUtils.show(mContext,jr.getMsg());
                    hideProgress();
                }
            }
            @Override
            public void onError(Response<String> response) {
                ToastUtils.show(mContext,"操作失败");
                hideProgress();
            }
        });
    }

    private void setData(UserInfoBean bean) {
//        ImageLoader.getInstance().displayImage(bean.getImgUrl(),iv_head);
        DraweeController controller= Fresco.newDraweeControllerBuilder()
                .setUri(bean.getImgUrl())
//                .setTapToRetryEnabled(true)
                .setOldController(iv_head.getController())
                .build();
        iv_head.setController(controller);
        tv_sex.setText(StringUtils.isEmpty(bean.getSex())?"未知":bean.getSex().equals("MAN")?"男":"女");
        sex=StringUtils.isEmpty(bean.getSex())?-1:bean.getSex().equals("MAN")?0:1;
        tv_user_name.setText(StringUtils.isEmpty(bean.getNick())?"未知":bean.getNick());
        tv_qianming.setText(StringUtils.isEmpty(bean.getPersonalizedSignature())?"":bean.getPersonalizedSignature());
        userName=bean.getNick();
        qianming=bean.getPersonalizedSignature();
        MyApplication.editor.putString(HYContent.NickName, bean.getNick());
        MyApplication.editor.putString(HYContent.AvatarUrl, bean.getImgUrl());
        MyApplication.editor.putString(HYContent.Gender, bean.getSex());
        MyApplication.editor.commit();
    }

    public void onClick(View view) {
        if (view.getId()==R.id.re_user_head){
            mIntent=new Intent(mContext,SetUserHeadActivity.class);
            startActivityForResult(mIntent,USER_HAND_CODE);

        }else if (view.getId()==R.id.re_name){
            mIntent=new Intent(mContext,UserNameActivity.class);
            mIntent.putExtra("source","name");
            mIntent.putExtra("name",userName);
            startActivityForResult(mIntent,USER_NAME_CODE);

        }else if (view.getId()==R.id.re_qianming){
            mIntent=new Intent(mContext,UserNameActivity.class);
            mIntent.putExtra("source","qiaming");
            mIntent.putExtra("name",qianming);
            startActivityForResult(mIntent,QIAN_MING_CODE);

        }else if (view.getId()==R.id.re_sex){
            mIntent=new Intent(mContext,SexSelectActivity.class);

            Bundle bundle=new Bundle();
            bundle.putInt("sexXingbie",sex);
            mIntent.putExtras(bundle);
            startActivityForResult(mIntent,SEX_CODE);

        }
        else if (view.getId()==R.id.re_location){
            //显示
            showLocationDialog();
//            if (ll_listViews.getVisibility()==View.VISIBLE){
//                ll_listViews.setVisibility(View.GONE);
//            }else{
//                ll_listViews.setVisibility(View.VISIBLE);
//
//            }
        }
    }

    private void showLocationDialog() {
        BottomSelectAreaDialog catogryBottomDialog=new BottomSelectAreaDialog(userId,"selectArea", new BottomSelectAreaDialog.IEditAreaClick() {
            @Override
            public void editArearClick(String city) {
                tv_location.setText(city);
            }
        });
        catogryBottomDialog.showDialog(mContext);
    }

    //    private void showLocationDialog() {
//        //配置
//        CityConfig cityConfig = new CityConfig.Builder(mContext)
//                .title("选择城市")//标题
//                .titleTextColor("#585858")//标题文字颜  色
//                .titleBackgroundColor("#E9E9E9")//标题栏背景色
//                .confirTextColor("#585858")//确认按钮文字颜色
//                .cancelTextColor("#585858")//取消按钮文字颜色
//                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
//                .showBackground(true)//是否显示半透明背景
//                .visibleItemsCount(7)//显示item的数量
//                .province("河北")//默认显示的省份
//                .city("石家庄")//默认显示省份下面的城市
//                .district("裕华区")//默认显示省市下面的区县数据
//                .provinceCyclic(true)//省份滚轮是否可以循环滚动
//                .cityCyclic(true)//城市滚轮是否可以循环滚动
//                .districtCyclic(true)//区县滚轮是否循环滚动
////                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
////                .setCustomItemTextViewId(R.id.item_city_name_tv)//自定义item布局里面的textViewid
////                .drawShadows(false)//滚轮不显示模糊效果
////                .setLineColor("#03a9f4")//中间横线的颜色
////                .setLineHeigh(5)//中间横线的高度
////                .setShowGAT(true)//是否显示港澳台数据，默认不显示
//                .build();
//        mPicker=new CityPickerView();
//        //监听选择点击事件及返回结果
//        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
//            @Override
//            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
//                super.onSelected(province, city, district);
//                location=city.getName()+"  "+district.getName();
//                tv_location.setText(location);
//                setDiQu();
//            }
//
//            @Override
//            public void onCancel() {
//                super.onCancel();
//            }
//        });
//        mPicker.show();
//    }

    private void submit(int resultCode) {
        DialogUtil.showProgress(mContext);
        Map<String, String> param = new HashMap<>();
        param.put("userId",userId);
        if (resultCode==USER_NAME_CODE){
            param.put("nick",userName);
        }
        if (resultCode==QIAN_MING_CODE){
            param.put("personalizedSignature",qianming);
        }
        String sex1 ="";
        if (resultCode==SEX_CODE){
            sex1 =sex==-1?Constant.MAN:sex==0? Constant.MAN :Constant.WOMEN;
            param.put("sex",sex1);
        }
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url= new HYContent().EDIT_USER_INFO;
        String finalSex = sex1;
        OkGo.<String>post(url).params(param).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                final int code = jr.getCode();
                if (resultCode==USER_NAME_CODE){
                    MyApplication.editor.putString(HYContent.LOGIN_NAME,userName);
                    MyApplication.editor.putString(HYContent.NickName, userName);
                }
                if (resultCode==SEX_CODE){
                    MyApplication.editor.putString(HYContent.Gender, finalSex);
                }
                MyApplication.editor.commit();
                hideProgress();
                ToastUtils.show(mContext,jr.getMsg());
            }
            @Override
            public void onError(Response<String> response) {
                ToastUtils.show(mContext,"操作失败");
                hideProgress();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==USER_NAME_CODE&&resultCode==HYContent.SUCCESS_CODE){
//            姓名设置成功
            userName = data.getStringExtra("name");
            tv_user_name.setText(userName);

            submit(requestCode);
        }else if (requestCode==QIAN_MING_CODE&&resultCode==HYContent.SUCCESS_CODE){
//            个性签名
            qianming = data.getStringExtra("name");
            tv_qianming.setText(qianming);
            submit(requestCode);
        }else if (requestCode==SEX_CODE&&resultCode==HYContent.SUCCESS_CODE){
//            性别设置成功
            sex = data.getIntExtra("sex",0);
            tv_sex.setText(sex==0?"男":"女");
            submit(requestCode);
        }else if (requestCode==USER_HAND_CODE){
//            头像设置成功
//            userHead = data.getStringExtra("userHead");
//            ImageLoader.getInstance().displayImage(userHead,iv_head);
            initData();

        }
    }
}